package com.appclub.tongyi;
import com.alibaba.dashscope.aigc.conversation.ConversationParam;
import com.alibaba.dashscope.aigc.conversation.Conversation;
import com.alibaba.dashscope.aigc.conversation.ConversationResult;
import com.alibaba.dashscope.utils.Constants;
//import com.alibaba.dashscope.utils.JsonUtils;
//import com.alibaba.fastjson.JSONObject;
//import com.alibaba.fastjson.JSON;
//import com.alibaba.dashscope.aigc.generation.GenerationResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import okhttp3.*;
import java.io.*;
import org.json.JSONObject;

@RestController
public class MyController {

    @GetMapping("/greet")
    public String greet(@RequestParam(name = "name", defaultValue = "World") String name) {
        return "Hello, " + name + "!";
    }

    @GetMapping("appty")
    public String appty(@RequestParam(name = "question") String question) {
        try {
            Constants.apiKey = "sk-15fba4c0111342b4818f552eccaaaa8b";
            Conversation conversation = new Conversation();
            String prompt = question;
            ConversationParam param = ConversationParam
                    .builder()
                    .model(Conversation.Models.QWEN_TURBO)
                    .prompt(prompt)
                    .build();
            ConversationResult result = conversation.call(param);
            System.out.println(result.getOutput().getText());
            return result.getOutput().getText();
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject errorResult = new JSONObject();
            try {
                errorResult.put("error", e.getMessage());
            } catch (JSONException ex) {
                throw new RuntimeException(ex);
            }
            return errorResult.toString();
        }
    }


    public static final String API_KEY = "ZlQ2nSxezwaPkhi4G2U8zqy8";
    public static final String SECRET_KEY = "n4iq0ef2kkhRDrrkHFE354Gbod1k6xC9";
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    @GetMapping("appbd")
    public String appbd(@RequestParam(name = "question") String question) {
        try {
            MediaType mediaType = MediaType.parse("application/json");

            JSONObject messagesJson = new JSONObject();
            messagesJson.put("role", "user");
            messagesJson.put("content", question);

            JSONArray messagesArray = new JSONArray();
            messagesArray.put(messagesJson);

            JSONObject requestBodyJson = new JSONObject();
            requestBodyJson.put("messages", messagesArray);
            requestBodyJson.put("temperature", 0.95);
            requestBodyJson.put("top_p", 0.8);
            requestBodyJson.put("penalty_score", 1);
            requestBodyJson.put("disable_search", false);
            requestBodyJson.put("enable_citation", false);
            requestBodyJson.put("response_format", "text");

            String json = requestBodyJson.toString();
            RequestBody body = RequestBody.create(mediaType,json);
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
//            System.out.println(response.body().string());
//            return response.body().string();
            // 解析JSON响应体到JSONObject
            String responseBody = response.body().string();
            JSONObject jsonObject = new JSONObject(responseBody);

            // 提取result字段的值
            String result = jsonObject.getString("result");

            // 打印result
            System.out.println(result);

            // 返回result
            return result;

        } catch (Exception e) {
//            e.printStackTrace();
//            // 如果发生异常，可以返回一个包含错误信息的JSONObject
//            JSONObject errorResult = new JSONObject();
//            try {
//                errorResult.put("error", e.getMessage());
//            } catch (JSONException ex) {
//                throw new RuntimeException(ex);
//            }
            return null;
        }
    }
    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
}
